package com.qinge.blog;


import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.sql.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author QDW
 * @date 2022/4/27 11:13
 * @description MySQL数据表生成实体类
 **/
public class GenEntityByMySQL {
    // 指定实体生成所在包的路径
    private String packageOutPath = "com.qinge.blog.entity";
    // 作者名字
    private String authorName = "QDW";
    // 列名数组
    private String[] colnames;
    // 列名类型数组
    private String[] colTypes;
    // 列名大小数组
    private int[] colSizes;
    // 字段注释
    private Map comment;
    // 是否需要导入包java.util.*
    private boolean importUtilFlag = true;
    // 是否需要导入包java.sql.*
    private boolean importSQLFlag = false;
    // 是否需要导入lombok
    private boolean lombokFlag=false;
    // 是否使用mybatis-plus
    private boolean mybatisPlusFlag=true;
    // 是否需要导入swagger
    private  boolean swaggerFlag=true;

    // 数据库连接
    private static final String URL = "jdbc:mysql://localhost:3306/qinge_blog?serverTimezone=Asia/Shanghai&characterEncoding=utf8&autoReconnect=true";
    private static final String NAME = "root";
    private static final String PASS = "root";
    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
    // 表名前缀
    private static final String TABLE_PREFIX ="blog";

    /*
     * 构造函数
     */
    public GenEntityByMySQL() {

        // 创建连接
        Connection con = null;
        // 查要生成实体类的表
        String SQLStr = String.format("SELECT table_name FROM information_schema.TABLES WHERE table_name like '%s_%%'", TABLE_PREFIX);
        List<String> tableNames =new ArrayList<>(16);

        try {
            try {
                Class.forName(DRIVER);
            } catch (ClassNotFoundException e1) {
                e1.printStackTrace();
            }
            con = DriverManager.getConnection(URL, NAME, PASS);
            PreparedStatement pStemt = con.prepareStatement(SQLStr);
            ResultSet resultSet = pStemt.executeQuery();
            while(resultSet.next()){
                tableNames.add(resultSet.getString("table_name"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        for (String tableName: tableNames){
            generateEntityByTable(tableName);
        }
    }


    /*
     * 构造函数
     */
    public void generateEntityByTable(String tablename) {

        // 创建连接
        Connection con = null;
        // 查要生成实体类的表
        String sql = "select * from " + tablename;
        PreparedStatement pStemt = null;
        PreparedStatement pStemt2 = null;
        try {
            try {
                Class.forName(DRIVER);
            } catch (ClassNotFoundException e1) {
                e1.printStackTrace();
            }
            con = DriverManager.getConnection(URL, NAME, PASS);
            pStemt = con.prepareStatement(sql);
            ResultSetMetaData rsmd = pStemt.getMetaData();
            int size = rsmd.getColumnCount();    //统计列
            colnames = new String[size];
            colTypes = new String[size];
            colSizes = new int[size];
            for (int i = 0; i < size; i++) {
                colnames[i] = rsmd.getColumnName(i + 1);
                colTypes[i] = rsmd.getColumnTypeName(i + 1);

                if (colTypes[i].equalsIgnoreCase("datetime")) {
                    importUtilFlag = true;
                }
                if (colTypes[i].equalsIgnoreCase("image") || colTypes[i].equalsIgnoreCase("text")) {
                    importSQLFlag = true;
                }
                colSizes[i] = rsmd.getColumnDisplaySize(i + 1);
            }

            //获取数据库字段注释
            String commentSql = " show full fields from " + tablename;
            comment = new HashMap();
            pStemt2 = con.prepareStatement(commentSql);
            ResultSet rs2 = pStemt2.executeQuery();
            while (rs2.next()) {
                String comm = rs2.getString("Comment");
                if (null != comm && !comm.equals("")) {
                    System.out.println(comm);
                    comment.put(rs2.getString("Field"), comm);
                } else {
                    comment.put(rs2.getString("Field"), rs2.getString("Field"));
                }
            }
            System.out.println(comment);
            String content = parse(colnames, colTypes, colSizes, tablename);

            try {
                File directory = new File("");
                // 自定义的实体类的目录domain/pojo/entity都行
                //  String outputPath = directory.getAbsolutePath() + "\\src\\main\\java\\" + this.packageOutPath.replace(".", "\\") + "\\";
                String outputPath = directory.getAbsolutePath() + "\\blog-entity\\src\\main\\java\\" + this.packageOutPath.replace(".", "\\") + "\\";
                File file = new File(outputPath);
                file.mkdirs();
                FileWriter fw = new FileWriter(outputPath + bigCamelize(tablename) + ".java");
                PrintWriter pw = new PrintWriter(fw);
                pw.println(content);
                pw.flush();
                pw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * @author QDW
     * @date 2022/4/27 12:29
     * @description 生成实体类主体代码
     * @param colnames
     * @param colTypes
     * @param colSizes
     * @param rawTaleName
     * @return java.lang.String
     **/
    private String parse(String[] colnames, String[] colTypes, int[] colSizes, String rawTaleName) {
        String tableName =bigCamelize(rawTaleName);
        StringBuffer sb = new StringBuffer();
        sb.append("package " + this.packageOutPath + ";\r\n");
        sb.append("\r\n");

        if(!mybatisPlusFlag){
            sb.append("import java.io.Serializable;\r\n");
        }

        //判断是否导入工具包
        if (importUtilFlag) {
            sb.append("import java.util.Date;\r\n");
        }
        if (importSQLFlag) {
            sb.append("import java.sql.*;\r\n");
        }
        if(lombokFlag){
            sb.append("import lombok.Data;\r\n");
        }

        if(mybatisPlusFlag){
            sb.append("import com.baomidou.mybatisplus.annotation.IdType;\r\n" +
                    "import com.baomidou.mybatisplus.annotation.TableField;\r\n" +
                    "import com.baomidou.mybatisplus.annotation.TableId;\r\n" +
                    "import com.baomidou.mybatisplus.annotation.TableName;\r\n" +
                    "import com.baomidou.mybatisplus.extension.activerecord.Model;\r\n");
        }

        if(swaggerFlag){
            sb.append("import io.swagger.annotations.ApiModel;\r\n");
            sb.append("import io.swagger.annotations.ApiModelProperty;\r\n");
        }

        // 写入数据库日期注解
        sb.append("import com.alibaba.fastjson.annotation.JSONField;\r\n");
        // 前端返回日期格式
        sb.append("import com.fasterxml.jackson.annotation.JsonFormat;\r\n");

        // 注释部分
        sb.append("\r\n");
        sb.append("/**\r\n");
        sb.append(String.format(" * @author %s\r\n", this.authorName));
        sb.append(String.format(" * @date %s\r\n", getSysdate()));
        sb.append(String.format(" * @description %s 实体类 \r\n", tableName));
        sb.append(" */ \r\n");

        // 实体部分
        if(lombokFlag){
            sb.append("\r\n");
            sb.append("@Data");
            sb.append("\r\n");
        }

        if(mybatisPlusFlag){
            sb.append(MessageFormat.format("@TableName(\"{0}\")\r\n", rawTaleName));
        }

        if(swaggerFlag){
            sb.append(MessageFormat.format("@ApiModel(value=\"{0}实体类\", description=\"{0}实体类\")\r\n", tableName));
        }

        if(mybatisPlusFlag){
            sb.append(MessageFormat.format("public class {0} extends Model<{0}> '{'\r\n",tableName));
        }else{
            sb.append(MessageFormat.format("public class {0} implements Serializable '{'\r\n", tableName));
        }

        sb.append("\r\n\tprivate static final long serialVersionUID = 1L;\r\n");

        // 属性
        processAllAttrs(sb);
        // get set方法
        processAllMethod(sb);
        sb.append("}\r\n");

        return sb.toString();
    }

    /**
     * 功能：生成所有属性
     *
     * @param sb
     */
    private void processAllAttrs(StringBuffer sb) {
        for (int i = 0; i < colnames.length; i++) {
            sb.append(String.format("\n" +
                    "\t/**\n" +
                    "\t * %s\n" +
                    "\t */\n" ,comment.get(colnames[i])));

            if(mybatisPlusFlag){
                if("id".equals(colnames[i])){
                    sb.append("\t@TableId(value = \"id\", type = IdType.ASSIGN_ID)\r\n");
                }else{
                    sb.append(String.format("\t@TableField(\"%s\")\r\n", colnames[i]));
                }
            }

            // 对Datel类型单独处理
            if("Date".equals(sqlType2JavaType(colTypes[i]))){
                sb.append("\t@JSONField(format=\"yyyy-MM-dd HH:mm:ss\")\r\n");
                sb.append("\t@JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\", timezone = \"GMT+8\")\r\n");
            }

            if(swaggerFlag==true){
                if("id".equals(colnames[i])){
                    sb.append(String.format("\t@ApiModelProperty(value = \"主键id\", position = %s)\r\n",i));
                }else{
                    sb.append(String.format("\t@ApiModelProperty(value = \"%s\", position = %s)\r\n",comment.get(colnames[i]).toString().trim(), i));
                }
            }

            sb.append(String.format( "\tprivate %s %s; \r\n",sqlType2JavaType(colTypes[i]),smallCamelize(colnames[i])));
        }

    }

    /**
     * @author QDW
     * @date 2022/4/27 12:21
     * @description 生成getter和setter方法
     * @param sb
     * @return void
     **/
    private void processAllMethod(StringBuffer sb) {
        sb.append("\r\n");
        for (int i = 0; i < colnames.length; i++) {
            sb.append("\tpublic void set" + bigCamelize(colnames[i]) + "(" + sqlType2JavaType(colTypes[i]) + " " +
                    smallCamelize(colnames[i]) + "){\r\n");
            sb.append("\t\tthis." + smallCamelize(colnames[i]) + "=" + smallCamelize(colnames[i]) + ";\r\n");
            sb.append("\t}\r\n\r\n");
            sb.append("\tpublic " + sqlType2JavaType(colTypes[i]) + " get" + bigCamelize(colnames[i]) + "(){\r\n");
            sb.append("\t\t\treturn " + smallCamelize(colnames[i]) + ";\r\n");
            sb.append("\t}\r\n\r\n");
        }

    }

    /**
     * 功能：获得列的数据类型
     *
     * @param sqlType
     * @return
     */
    private String sqlType2JavaType(String sqlType) {

        if (sqlType.equalsIgnoreCase("bit")) {
            return "Boolean";
        } else if (sqlType.equalsIgnoreCase("tinyint")) {
            return "Byte";
        } else if (sqlType.equalsIgnoreCase("smallint")) {
            return "Short";
        } else if (sqlType.equalsIgnoreCase("int")) {
            return "Integer";
        } else if (sqlType.equalsIgnoreCase("bigint")) {
            return "Long";
        } else if (sqlType.equalsIgnoreCase("float")) {
            return "Float";
        } else if (sqlType.equalsIgnoreCase("decimal") || sqlType.equalsIgnoreCase("numeric")
                || sqlType.equalsIgnoreCase("real") || sqlType.equalsIgnoreCase("money")
                || sqlType.equalsIgnoreCase("smallmoney") || sqlType.equalsIgnoreCase("double")) {
            return "Double";
        } else if (sqlType.equalsIgnoreCase("varchar") || sqlType.equalsIgnoreCase("char")
                || sqlType.equalsIgnoreCase("nvarchar") || sqlType.equalsIgnoreCase("nchar")
                || sqlType.equalsIgnoreCase("text") || sqlType.equalsIgnoreCase("longtext")) {
            return "String";
        } else if (sqlType.equalsIgnoreCase("datetime") || sqlType.equalsIgnoreCase("timestamp")) {
            return "Date";
        } else if (sqlType.equalsIgnoreCase("image")) {
            return "Blod";
        }

        return null;
    }

    /**
     * 获取系统当前时间
     *
     * @param
     * @return
     * @explain 使用Date实现
     */
    public static String getSysdate() {
        Date date = new Date(System.currentTimeMillis());

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        return dateFormat.format(date);
    }


    /**
     * 数据表字段名转换为驼峰式名字的实体类属性名
     *
     * @param tabAttr 数据表字段名
     * @return 转换后的驼峰式命名
     */
    public static String smallCamelize(String tabAttr) {
        if (isBlank(tabAttr)) {
            return tabAttr;
        }
        Pattern pattern = Pattern.compile("(.*)_(\\w)(.*)");
        Matcher matcher = pattern.matcher(tabAttr);
        if (matcher.find()) {
            return smallCamelize(matcher.group(1) + matcher.group(2).toUpperCase() + matcher.group(3));
        } else {
            return tabAttr;
        }
    }

    /**
     * @author QDW
     * @date 2022/4/27 12:07
     * @description 大驼峰命名发
     * @param tabAttr
     * @return java.lang.String
     **/
    public static String bigCamelize(String tabAttr) {
        if (isBlank(tabAttr)) {
            return tabAttr;
        }
        return smallCamelize("_"+tabAttr);
    }

    public static  boolean isBlank(String str){
       if(str==null || str.length()==0){
           return true;
       }else{
           return false;
       }
    }

    /**
     * 执行方法
     *
     * @param args
     */
    public static void main(String[] args) {

        // tabesNames的数据是通过准备工作的第4步得来的
        new GenEntityByMySQL();
    }
}
